package first.endtoend.authentification

import first.endtoend.Agent
import first.endtoend.User
import first.endtoend.messages.MessageCode
import grails.converters.JSON
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.WebAttributes
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

import javax.servlet.http.HttpServletResponse

class LoginController
{
    /**
     * Dependency injection for the authenticationTrustResolver.
     */
    def authenticationTrustResolver

    /**
     * Dependency injection for the springSecurityService.
     */
    def springSecurityService


    def beforeInterceptor = {


        String agent = request.getHeader("User-Agent")

        /* if (agentInstance.sessionIsActive!=null ) {
             if(agentInstance.sessionIsActive==true){
                 render([code:MessageCode.NOT_FOUND.value(), error: 'access denied'] as JSON)

                 return
             }
             return
         }*/
    }

    /**
     * Default action; redirects to 'defaultTargetUrl' if logged in, /login/auth otherwise.
     */

    def index = {
        def agentInstance = springSecurityService.currentUser as Agent
        if (springSecurityService.isLoggedIn())
        {

            agentInstance.sessionIsActive = true
            agentInstance.save()
            redirect uri: SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl

        } else
        {
            redirect action: 'auth', params: params
        }
    }

    /**
     * Show the login page.
     */
    def auth = {

        println 'login'
        def config = SpringSecurityUtils.securityConfig
        String agent = request.getHeader("User-Agent")
        println agent + "  AGENT"

        if (springSecurityService.isLoggedIn())
        {
            if (agent.equals("first"))
            {
                def user = springSecurityService.currentUser as Agent
                println("**** params sent from agent :" + params)
                render(code: MessageCode.SUCCESS.value(), user)
                return
            }
            redirect uri: config.successHandler.defaultTargetUrl
            return
        }
        if (agent.equals("first"))
        {
            render(code: MessageCode.NOT_FOUND.value(), error: "wrong username or password")
            return
        }
        String view = 'auth'
        String postUrl = "${request.contextPath}${config.apf.filterProcessesUrl}"
        render view: view, model: [postUrl            : postUrl,
                                   rememberMeParameter: config.rememberMe.parameter]
    }

    def success = {
    }

    /**
     * The redirect action for Ajax requests.
     */
    def authAjax = {
        response.setHeader 'Location', SpringSecurityUtils.securityConfig.auth.ajaxLoginFormUrl
        response.sendError HttpServletResponse.SC_UNAUTHORIZED
    }

    /**
     * Show denied page.
     */
    def denied = {

        if (springSecurityService.isAjax(request))
        {
            ajaxDenied()
        }
        if (springSecurityService.isLoggedIn() &&
                authenticationTrustResolver.isRememberMe(SCH.context?.authentication))
        {
            // have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
            redirect action: 'full', params: params
        }


    }

    /**
     * Login page for users with a remember-me cookie but accessing a IS_AUTHENTICATED_FULLY page.
     */
    def full = {
        def config = SpringSecurityUtils.securityConfig
        render view: 'auth', params: params,
                model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication),
                        postUrl  : "${request.contextPath}${config.apf.filterProcessesUrl}"]
    }

    /**
     * Callback after a failed login. Redirects to the auth page with a warning message.
     */
    def authfail = {

        def username = session[UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY]
        String msg = ''
        def exception = session[WebAttributes.AUTHENTICATION_EXCEPTION]
        if (exception)
        {
            if (exception instanceof AccountExpiredException)
            {
                msg = g.message(code: "springSecurity.errors.login.expired")
            } else if (exception instanceof CredentialsExpiredException)
            {
                msg = g.message(code: "springSecurity.errors.login.passwordExpired")
            } else if (exception instanceof DisabledException)
            {
                msg = g.message(code: "springSecurity.errors.login.disabled")
            } else if (exception instanceof LockedException)
            {
                msg = g.message(code: "springSecurity.errors.login.locked")
            } else
            {
                msg = g.message(code: "springSecurity.errors.login.fail")
            }
        }

        if (springSecurityService.isAjax(request))
        {
            render([error: msg, code: MessageCode.NOT_FOUND.value()] as JSON)
        } else
        {
            flash.message = msg

            redirect action: 'auth', params: params
        }
    }

    /**
     * The Ajax success redirect url.
     */
    def ajaxSuccess = {

        render([code: MessageCode.SUCCESS.value(), user: springSecurityService.currentUser as User] as JSON)
    }

    /**
     * The Ajax denied redirect url.
     */
    def ajaxDenied = {
        render([code: MessageCode.NOT_FOUND.value(), error: 'access denied'] as JSON)
    }
}